package com.cnnp.dip.business.service.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cnnp.dip.api.client.GrafanaAnnotationApi;
import com.cnnp.dip.business.common.util.BeanUtil;
import com.cnnp.dip.business.entity.Annotation;
import com.cnnp.dip.business.repository.AlertDataMapper;
import com.cnnp.dip.business.service.AnnotationService;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class AnnotationServiceImpl implements AnnotationService {

    @Autowired
    private AlertDataMapper alertDataMapper;

    @Autowired
    private GrafanaAnnotationApi grafanaAnnotationApi;

    @Override
    public void saveAlert(Annotation annotation) {
        // 生成 grafanaId：time + alertId
        String grafanaId = annotation.getTime() + "-" + annotation.getId(); // 使用 time 字段

        // 根据 grafanaId 查询数据是否存在
        Annotation existingData = alertDataMapper.selectOne(new QueryWrapper<Annotation>().eq("grafana_id", grafanaId));
        if (existingData != null) {
            // 数据已存在，直接返回
            return;
        }

        // 强制忽略请求体中的 id，让数据库自动生成
        annotation.setId(null);

        // 设置 grafanaId
        annotation.setGrafanaId(grafanaId);

        // 设置 status 为 0（未确认）
        annotation.setStatus(0);

        // 保存数据
        alertDataMapper.insert(annotation);

        // 记录日志
        log.info("Saved alert data: {}", annotation);
    }

    @Override
    public List<Annotation> getAllAnnotations() {
        return alertDataMapper.selectList(null);
    }

    @Override
    public List<Map<String, Object>> fetchAnnotations(int limit, boolean matchAny, String dashboardUID, int panelId) {
        // 1. 调用Grafana API获取所有数据，最多获取limit条
        List<Map<String, Object>> allAnnotations = grafanaAnnotationApi.getAnnotations(limit, matchAny, dashboardUID, panelId);
        
        // 2. 将获取的记录倒序保存到PSQL中
        for (int i = allAnnotations.size() - 1; i >= 0; i--) {
            Map<String, Object> annotation = allAnnotations.get(i);
            Annotation alertData = new Annotation();
            BeanUtil.copyProperties(annotation, alertData);
            alertData.setDashboardUID(dashboardUID);
            alertData.setPanelId(panelId);
            saveAlert(alertData);
        }
        
        // 3. 返回所有数据，由前端处理分页
        return allAnnotations;
    }
} 